import { isValid, Node } from "cc";
import { FrameProp } from "../Base/FrameProp";
import CommonUtil from "../CommonUtil";
import FrameBase from "../FrameBase";

export default class FrameUIMgr extends FrameBase {
    private static _instance: FrameUIMgr = null;
    public static get Instance(): FrameUIMgr {
        if (!this._instance) {
            this._instance = new FrameUIMgr();
        }
        return this._instance;
    }

    private cacheProp: Map<string, FrameProp> = new Map();
    private propContainer: Array<FrameProp> = [];

    /**
     * 打开弹窗
     * @param name 弹窗名称
     * @param bundleName 弹窗所在包名（默认resources）
     */
    public async openProp(name: string, ...args:any): Promise<Node> {
        let prop = await CommonUtil.loadProp(name);
        let sp = prop.getComponent(FrameProp);
        sp.args = args;
        this.cacheProp.set(name, sp);

        this.propContainer.push(sp);
        return Promise.resolve(prop);
    }

    /**
     * 关闭弹窗
     * @param name 弹窗名
     */
    public closeProp(name?: string) {
        let sp = null;
        if(name){
            sp = this.cacheProp.get(name);
        }else{
            sp = this.propContainer[this.propContainer.length - 1];
        }
        sp.close();
        this.checkCache();
    }

    /**检查缓存 */
    private checkCache() {
        this.cacheProp.forEach((sp: FrameProp, name: string) => {
            if (isValid(sp.node)) {
                this.cacheProp.delete(name);
            }
        })
        this.propContainer.forEach((sp: FrameProp, index: number) => {
            if (isValid(sp.node)) {
                this.propContainer.splice(index, 1);
            }
        })
    }
}